package com.misty.blog.controller.blogController;

import com.misty.blog.bean.param.blog.FetchSuggestParam;
import com.misty.blog.bean.param.tag.TagSaveParam;
import com.misty.blog.service.TagService;
import com.misty.common.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/fore/tag")
@Slf4j
//@PreAuthorize("hasAuthority('tag')")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("/fetchTagList")
    public Result<?> fetchTagList(FetchSuggestParam param){
        return tagService.getAllTag();
    }

    @GetMapping("/selectTagNameByUser")
    public Result<?> selectTagNameByUser(Integer userId){
        return tagService.selectTagNameByUser(userId);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('fore/tag')")
    public Result<?> save(@RequestBody TagSaveParam param){

        //获取该博客的所有标签
        Result<List<String>> tagNameByBlog = tagService.selectTagNameByBlog(param.getBlogId());
        //没有任何标签，则直接添加
        if(tagNameByBlog.getCode() == -1){
            Result<?> result = tagService.addAllTag(param.getTagList(), param.getBlogId());
            if(result.isErrorResult()){
                return Result.error("保存标签失败!");
            }
            return Result.success("保存标签成功!");
        }

        List<String> curTagList = tagNameByBlog.getData();
        List<String> tmpTagList = param.getTagList();

        //假如接收到的tagList 和 目前所有标签一样，则不用修改
        if(curTagList.containsAll(tmpTagList) && curTagList.size() == tmpTagList.size()){
            return Result.success("保存标签成功!");
        }

        //假如增加
        List<String> add = tmpTagList.stream()
                .filter(tag -> !curTagList.contains(tag))
                .collect(Collectors.toList());
        Result<?> result = tagService.addAllTag(add, param.getBlogId());
        if(result.isErrorResult()){
            return Result.error("保存标签失败!");
        }

        //假如删除
        List<String> remove = curTagList.stream()
                .filter(tag -> !tmpTagList.contains(tag))
                .collect(Collectors.toList());
        Result<?> result1 = tagService.removeAllTag(remove, param.getBlogId());
        if(result1.isErrorResult()){
            return Result.error("保存标签失败!");
        }

        return Result.success("保存标签成功!");
    }

}
